/**
 * Created by Shaka on 12/21/16.
 */

var Config = {
    selectUrl: "/api/admin/orders",
    updateUrl:"/api/admin/orders",
    updateUrlForCellEdit: '/api/admin/order/cellEdit',
    selectExcelUrl: "/api/admin/orders/excel/list"
};

$(document).ready(function () {
    $(".datepicker").datepicker({
        language: "zh-CN",
        clearBtn: true,//清除按钮
        todayBtn: "linked",//今日按钮
        changeMonth: true,
        changeYear: true,
        autoclose: true,//选中之后自动隐藏日期选择框
        format: "yyyy-mm-dd"//日期格式，详见 http://bootstrap-datepicker.readthedocs.org/en/release/options.html#format
    });
    $.jgrid.defaults.styleUI = "Bootstrap";
    $("#data_list").jqGrid({
        datatype: "json",
        url: Config.selectUrl,
        postData: {auditStatus: 0,payStatus:1},
        height: 450,
        autowidth: true,
        shrinkToFit: true,
        rowNum: 12,
        colNames: ["编号", "订单编号","购买者", "审核状态","支付状态","订单状态", "实付金额", "收货地址","下单时间", "操作"],
        colModel: [{
            name: "orderId",
            index: "orderId",
            sorttype: "int",
            width: 5,
            search: true,
            key: true
        }, {
            name: "orderSn",
            index: "orderSn",
            width: 15,
            search: true
        }, {
            name: "nickName",
            index: "nickName",
            width: 15
        },{
            name: "auditStatus",
            index: "auditStatus",
            sorttype: "int",
            width: 7,
            editoptions: {value: "0:未审核;1:审核通过;2:审核未通过"},
            editable: true,
            edittype: 'select',
            formatter: 'select'
        },{
            name: "payStatus",
            index: "payStatus",
            sorttype: "int",
            width: 7,
            editoptions: {value: "0:未支付;1:已支付;11:支付未完成"},
            editable: false,
            edittype: 'select',
            formatter: 'select'
        }, {
            name: "orderStatus",
            index: "orderStatus",
            sorttype: "int",
            width: 7,
            editoptions: {value: "0:待发货;1:已发货;2:已支付;3:退货;4:退款;5:交易关闭;6:已收货"},
            editable: true,
            edittype: 'select',
            formatter: 'select'
        },{
            name: "orderAmount",
            index: "orderAmount",
            width: 7,
            sortable: false
        }, {
            name: "shippingAddress",
            index: "shippingAddress",
            width: 30,
            sortable: false
        }, {
            name: "ctime",
            index: "ctime",
            width: 12,
            sortable: false
        }, {
            name: "operate",
            index: "operate",
            width: 17,
            sortable: false
        }],
        cellEdit: true,
        cellsubmit: 'remote',
        cellurl: Config.updateUrlForCellEdit,
        multiselect: false,
        multiboxonly: true,

        pager: "#pager_data_list",
        viewrecords: true,
        hidegrid: false,
        jsonReader: {
            root: "data", "page": "page", total: "total",
            records: "records", repeatitems: false, id: "orderId"
        },
        gridComplete: function () {
            dataWrapper();
        }
    });
    jQuery("#data_list").jqGrid('navGrid', '#pager_data_list', {add: false, edit: false, del: false,search: false});
    $(window).bind("resize", function () {
        var width = $(".jqGrid_wrapper").width();
        $("#data_list").setGridWidth(width);
    });
});

function Delete(id, index) {
    updateDialog("DELETE", Config.deleteUrl + '/' + id);
    jQuery("#data_list").jqGrid('delRowData', id);
}

function updateDialog(action, url) {
    $.ajax(
        {
            url: url,
            type: action,
            success: function (data, textStatus, jqXHR) {
                if (action == 'DELETE') {
                    jQuery("#data_list").setGridParam({url: url}).trigger("reloadGrid");

                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(errorThrown);
            }
        });
}
function dataWrapper() {
    var ids = jQuery("#data_list").jqGrid('getDataIDs');
    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        var dataFromTheRow = jQuery('#data_list').jqGrid('getRowData', id);
        dataFromTheRow.ctime = new Date(dataFromTheRow.ctime * 1).yyyymmddhhmmss();
        var html = "<a style='color:#f60;padding-right: 15px' onclick='orderUpdate(" + id + ")'>处理</a>";
        // html += '<a style="color:#f60;padding-right: 15px" onclick="orderProfit(\'' + dataFromTheRow.orderSn + '\')" >返利详情</a>';
        html += '<a class="J_menuItem" style="color:#f60;padding-right: 15px" href="/api/admin/orders/excel/' + dataFromTheRow.orderSn + '" >订单导出</a>';
        jQuery("#data_list").jqGrid('setRowData', ids[i], {orderAmount:toFixedForPrice(dataFromTheRow.orderAmount),ctime: dataFromTheRow.ctime,operate: html});
    }
}

function dataWrapper1(subgrid_table_id) {
    var ids = jQuery("#" + subgrid_table_id).jqGrid('getDataIDs');
    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        var dataFromTheRow = jQuery("#" + subgrid_table_id).jqGrid('getRowData', id);
        jQuery("#" + subgrid_table_id).jqGrid('setRowData', ids[i], {amount:toFixedForPrice(dataFromTheRow.amount)});
    }
}

function orderUpdate(id) {
    layer.open({
        type: 2,
        //   title: '请选择区域',
        scrollbar: false,
        shadeClose: true,
        shade: 0.8,
        area: ['100%', '100%'],
        content: "/orders/update/"+id
    })
}
function orderProfit(orderSn) {
    layer.open({
        type: 2,
        //   title: '请选择区域',
        scrollbar: false,
        shadeClose: true,
        shade: 0.8,
        area: ['100%', '100%'],
        content: "/web/parent_orders_profit.html?id="+orderSn
    })
}
$("#excel_list").click(function () {
    var postdata = $("#data_list").jqGrid('getGridParam', 'postData');
    postdata._search = true;
    postdata.stime = dateToEpoch($("#beginDate").val()) * 1 - 8 * 60 * 60 * 1000 + 1;
    postdata.etime = dateToEpoch($("#endDate").val()) * 1 + 16 * 60 * 60 * 1000 - 1;
    $("#excel_list").attr("href","/api/admin/orders/excel/list?stime="+postdata.stime+"&etime="+postdata.etime);
});
$("#perform_search").click(function () {
    var postdata = $("#data_list").jqGrid('getGridParam', 'postData');
    postdata._search = true;
    if($("#beginDate").val() != ""){
        postdata.stime = dateToEpoch($("#beginDate").val()) * 1 - 8 * 60 * 60 * 1000 + 1;
    }
    if($("#endDate").val() != ""){
        postdata.etime = dateToEpoch($("#endDate").val()) * 1 + 16 * 60 * 60 * 1000 - 1;
    }
    postdata.remark = $("#buyType") .val();
    jQuery("#data_list").trigger("reloadGrid",[{page: 1}]);
});
$("#batchSelect").change(function () {
    var selected = $(this).find("option:selected").val();
    if (selected == 1) {
        var auditStatusTrue = jQuery("#data_list").jqGrid('getGridParam', 'selarrrow');
        for (var s = 0; s < auditStatusTrue.length; s++) {
            console.log(s);
            $.ajax({
                url: Config.updateUrl,
                type: "PUT",
                data: {orderId: auditStatusTrue[s], auditStatus: 1},
                dataType: "json",
                async: false,
                success: function (data, textStatus, jqXHR) {
                    toastr.success(data.msg, data.title);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });

        }
    } else if (selected == 2) {
        var auditStatusFalse = jQuery("#data_list").jqGrid('getGridParam', 'selarrrow');
        for (var y = 0; y < auditStatusFalse.length; y++) {
            $.ajax({
                url: Config.updateUrl,
                type: "PUT",
                data: {orderId: auditStatusFalse[y], auditStatus: 2},
                dataType: "json",
                async: false,
                success: function (data, textStatus, jqXHR) {
                    toastr.success(data.msg, data.title);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
        }
    } else if (selected == 999) {
        var ids = jQuery("#data_list").jqGrid('getGridParam', 'selarrrow');
        for (var z = 0; z < ids.length; z++) {
            updateDialog("DELETE", Config.deleteUrl + '/' + ids[z], ids[z]);

        }
    }else if (selected > 20 || selected ==20){
        var num=selected % 20;
        var orderStatus = jQuery("#data_list").jqGrid('getGridParam', 'selarrrow');
        for (var y = 0; y < orderStatus.length; y++) {
            $.ajax({
                url: Config.updateUrl,
                type: "PUT",
                data: {orderId: orderStatus[y], orderStatus: num},
                dataType: "json",
                async: false,
                success: function (data, textStatus, jqXHR) {
                    toastr.success(data.msg, data.title);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    toastr.error(errorThrown, textStatus);
                }
            });
        }
    }
    $("#batchSelect").val("");
    jQuery("#data_list").trigger("reloadGrid");
});